package org.tracy.timewindow;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by dinghaiyun on 2016/11/29.
 */
public class TimeWindowDivide implements Runnable{
    @Override
    public void run() {
        Long first = null;
        Long last = null;
        List batch = null;
        while(true){
            try {
                TimeWindow timeWindow = TimeWindowQueue.take();
                if(timeWindow==null){
                    if(first != null && new Date().getTime() - first > TimeWindowQueue.TimeWindow && batch!=null && !batch.isEmpty()){
                        TimeWindowQueue.addBatchList(batch);
                        batch = new ArrayList();
                    }
                    Thread.sleep(300);
                    continue;
                }
                if(first == null ){
                    first = timeWindow.getTime();
                    batch = new ArrayList();
                }
                last = timeWindow.getTime();
                batch.add(timeWindow.getObject());
                if(last - first > TimeWindowQueue.TimeWindow){
                    TimeWindowQueue.addBatchList(batch);
                    first = last = null;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
